<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webGl No6</title>
    <script src="js/three73.js"></script>
    <script src="js/Stats.js"></script>
    <script src="js/dat.gui.js"></script>
    <script src="js/MTLLoader.js"></script>
    <script src="js/OBJMTLLoader.js"></script>


    <style>
        body{
            margin:0;
        }
    </style>
</head>
<body>
    <div id="WebGL-output"></div>
    <div id="Stats-output"></div>
    <script>
       window.onload = function () {
           var stats = initStats(); //调用stat函数
           var scene = new THREE.Scene(); //定义场景
           var camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,1000); //定义相机

           //定义渲染器
           var renderer = new THREE.WebGLRenderer();
           renderer.setClearColor(0xEEEEEE);
           renderer.setSize(window.innerWidth,window.innerHeight);

           renderer.shadowMapEnabled = true;
           renderer.shadowMapSoft = true; //软阴影

            //创建一个坐标轴
           var axex = new THREE.AxisHelper(20);
           scene.add(axex);

           //创建一个光源
           var spotLight = new THREE.SpotLight(0xffffff);
           spotLight.position.set(2,30,20);
           spotLight.castShadow = true;  //该光源能产生阴影
           scene.add(spotLight);

           var loader= new THREE.OBJMTLLoader();
           loader.addEventListener('load',function (event) {
               var obj = event.content;
               mesh = obj;
               scene.add(obj);
           });
           loader.load('images/car.obj','images/car.mtl');
           //输出到页面
           var webgl = document.getElementById('WebGL-output');
           webgl.appendChild(renderer.domElement);

           var controls = new function(){
               this.cameraPX = -30;
               this.cameraPY = 30;
               this.cameraPZ = 30;
           };

           var gui = new dat.GUI();
           gui.add(controls,'cameraPX',-100,100);
           gui.add(controls,'cameraPY',-100,100);
           gui.add(controls,'cameraPZ',-100,100);

           var step = 0.03;

           renderScene();

           function renderScene(){
               stats.update(); //实时更新

               camera.position.x = controls.cameraPX;
               camera.position.y = controls.cameraPY;
               camera.position.z = controls.cameraPZ;
               camera.lookAt(scene.position);
               requestAnimationFrame(renderScene);
               renderer.render(scene,camera);
           }

           function initStats(){  //初始化函数，定义具体位置
               var stats = new Stats();
               stats.setMode(0);
               stats.domElement.style.position = 'absolute';
               stats.domElement.style.left = '0px';
               stats.domElement.style.top = '0px';
               document.getElementById('Stats-output').appendChild(stats.domElement);
               return stats;
           }
       }
    </script>
</body>
</html>